using System;
using System.Collections.Generic;
using System.Text;
using ECommerce.Library.Web;
using Entity;
using ECommerce.DAL;
using ECommerce.Library;
using log4net;
using ECommerce.Library.DataStructure;

namespace AutoGear.BLL
{
    public class CustomerUser : AutoGearSiteUser
    {
        private UserRoleType _userRole;
        public UserRoleType UserRole
        {
            get { return _userRole; }
        }
        private UserProfile _profile;
        public UserProfile Profile
        {
            get { return _profile; }
        }

        public CustomerUser()
        {

        }

        public CustomerUser(TblUser tblUser, TblUserProfile tblUserProfile)
        {
            base._displayName = tblUserProfile.LastName + ", " + tblUserProfile.FirstName;
            base._loginUserName = tblUser.UserName;
            base._loginPassword = tblUser.Password;
            base._userId = tblUser.UserId;
            this._userRole = UserRoleType.CustomerUser;
            this._profile = new UserProfile(tblUserProfile);
            this._isActive = tblUser.IsActive;
            this._isDeleted = tblUser.IsDeleted;
        }

        public static CustomerUser Create(string firstName, string lastName, DateTime dateOfBirth, string emailAddress,
        Gender userGender, string userTelephoneNumber, string userFaxNumber, string companyName,
        string companyTelephoneNumber, string companyFaxNumber, Address billingAddress, Address shippingAddress,
            bool isActive, string loginEmailAddress, string loginPassword, string adminComment)
        {
            CustomerUser newCustomerUser = new CustomerUser();
            int userId = TblUser.CreateNewTblUser(loginEmailAddress, loginPassword, DateTime.Now, isActive, false);
            int userRoleId = TblUserRole.CreateNewTblUserRole(UserRoleType.CustomerUser.ToString(), isActive, false, userId);
            newCustomerUser._profile = UserProfile.Create(firstName, lastName, dateOfBirth, emailAddress, userGender, userTelephoneNumber, userFaxNumber, companyName, companyTelephoneNumber, companyFaxNumber, billingAddress, shippingAddress, isActive, userId, adminComment);
            newCustomerUser._userRole = UserRoleType.CustomerUser;
            newCustomerUser._displayName = newCustomerUser._profile.FirstName + " " + newCustomerUser._profile.LastName;
            newCustomerUser._loginPassword = loginPassword;
            newCustomerUser._loginUserName = loginEmailAddress;
            newCustomerUser._userId = userId;
            newCustomerUser._isActive = isActive;
            newCustomerUser._isDeleted = false;
            return newCustomerUser;
        }

        public static int TotalCustomerCount(string searchName, bool includeDeleted)
        {
            int count = 0;
            if (includeDeleted)
                count = TblUserExtended.GetCustomerUserCount(searchName);
            else
                count = TblUserExtended.GetNonDeletedCustomerUserCount(searchName);
            return count;
        }

        public static CustomerUser GetCustomerUserByUserName(string userName)
        {
            try
            {
                CustomerUser customerUser = new CustomerUser();
                ECommerce.DAL.CustomCollection<TblUser> tblUser = TblUserExtended.GetUserByUserName(userName);
                if (tblUser.Count > 0)
                {
                    int userId = tblUser[0].UserId;
                    ECommerce.DAL.CustomCollection<TblUserProfile> tblUserProfile = TblUserProfile.GetTblUserProfileByUserId(userId);
                    if (tblUserProfile.Count > 0)
                    {
                        customerUser = new CustomerUser(tblUser[0], tblUserProfile[0]);
                    }
                }
                return customerUser;
            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("GetCustomerUserByUserName caused server error: Parameters( ");
                logText = logText.Append("userName -> ").Append(userName);
                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("CustomerUser");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;
            }
        }

        public static CustomerUser GetCustomerUserByUserId(int userId)
        {
            try
            {
                CustomerUser customerUser = new CustomerUser();
                TblUser tblUser = TblUser.GetTblUserByUserId(userId);
                if (tblUser != null)
                {
                    ECommerce.DAL.CustomCollection<TblUserProfile> tblUserProfile = TblUserProfile.GetTblUserProfileByUserId(userId);
                    if (tblUserProfile.Count > 0)
                    {
                        customerUser = new CustomerUser(tblUser, tblUserProfile[0]);
                    }
                }
                return customerUser;
            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("GetCustomerUserByUserId caused server error: Parameters( ");
                logText = logText.Append("userId -> ").Append(userId);
                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("CustomerUser");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;
            }
        }

        public void Update()
        {
            TblUser tblUser = TblUser.GetTblUserByUserId(this._userId);
            if (tblUser != null)
            {
                tblUser.IsActive = this._isActive;
                tblUser.IsDeleted = this._isDeleted;
                //tblUser.Password = this._loginPassword;
                tblUser.Save();
            }
            ECommerce.DAL.CustomCollection<TblUserRole> tblUserRole = TblUserRole.GetTblUserRoleByUserId(this._userId);
            if (tblUserRole != null && tblUserRole.Count > 0)
            {
                tblUserRole[0].IsActive = this._isActive;
                tblUserRole[0].IsDeleted = this._isDeleted;
                tblUserRole[0].Save();
            }
            this.Profile.Update();
        }

        public static ReadWriteCustomCollection<CustomerUser> GetCustomerUser(string searchCustomerName,
            string sortBy, bool includeDeleted)
        {
            searchCustomerName = Security.BindStringInput(searchCustomerName, SecurityLevel.Zero);
            sortBy = Security.BindStringInput(sortBy, SecurityLevel.Zero);

            ECommerce.DAL.CustomCollection<TblUser> users = null;
            if (includeDeleted)
                users = TblUserExtended.GetAllCustomerUsers(searchCustomerName);
            else
                users = TblUserExtended.GetAllNonDeletedCustomerUsers(searchCustomerName, sortBy);

            return LoadFromCustomCollection(users);
        }

        public static ReadWriteCustomCollection<CustomerUser> GetCustomerUser(string searchCustomerName,
            string orderBy, int firstItemPosition, int maxItem, bool includeDeleted)
        {
            searchCustomerName = Security.BindStringInput(searchCustomerName, SecurityLevel.Zero);
            orderBy = Security.BindStringInput(orderBy, SecurityLevel.Zero);

            ECommerce.DAL.CustomCollection<TblUser> users = null;
            if (includeDeleted)
                users = TblUserExtended.GetCustomerUsersPaged(searchCustomerName, orderBy, firstItemPosition, maxItem);
            else
                users = TblUserExtended.GetNonDeletedCustomerUsersPaged(searchCustomerName, orderBy, firstItemPosition, maxItem);

            return LoadFromCustomCollection(users);
        }
        public static ReadWriteCustomCollection<CustomerUser> GetCustomerUserCondition(string condition,
           string orderBy, int firstItemPosition, int maxItem)
        {
            orderBy = Security.BindStringInput(orderBy, SecurityLevel.Zero);

            ECommerce.DAL.CustomCollection<TblUser> users = null;
            users = TblUserExtended.GetNonDeletedCustomerUsersCOnditionPaged(condition, orderBy, firstItemPosition, maxItem);

            return LoadFromCustomCollection(users);
        }

        public static int TotalCustomerConditionCount(string condition)
        {
            int count = 0;
            count = TblUserExtended.GetNonDeletedCustomerUserConditionCount(condition);
            return count;
        }

        public static ReadWriteCustomCollection<CustomerUser> GetCustomerUser(string orderBy, int firstItemPosition, int maxItem)
        {
           orderBy = Security.BindStringInput(orderBy, SecurityLevel.Zero);

            ECommerce.DAL.CustomCollection<TblUser> users = null;
            users = TblUserExtended.GetCustomerUsersPaged2(orderBy, firstItemPosition, maxItem);

            return LoadFromCustomCollection(users);
        }


        public static void DeleteCustomerUser(List<int> idList)
        {
            ReadWriteCustomCollection<CustomerUser> users = new ReadWriteCustomCollection<CustomerUser>();

            foreach (int id in idList)
            {
                users.Add(CustomerUser.GetCustomerUserByUserId(id));
            }
            DeleteCustomerUser(users);
        }

        public static void DeleteCustomerUser(ReadWriteCustomCollection<CustomerUser> customerUsers)
        {
            foreach (CustomerUser customerUser in customerUsers)
            {
                customerUser.Profile.IsDeleted = true;
                customerUser.IsDeleted = true;
                customerUser.Update();
            }
        }

        private static ReadWriteCustomCollection<CustomerUser> LoadFromCustomCollection(ECommerce.DAL.CustomCollection<TblUser> users)
        {
            ReadWriteCustomCollection<CustomerUser> loadedUsers = new ReadWriteCustomCollection<CustomerUser>();
            for (int i = 0; i < users.Count; i++)
            {
                ECommerce.DAL.CustomCollection<TblUserProfile> loadedProfiles = TblUserProfile.GetTblUserProfileByUserId(users[i].UserId);
                loadedUsers.Add(new CustomerUser(users[i], loadedProfiles[0]));
            }

            return loadedUsers;
        }



    }
}
